<?php
// 应用公共函数库文件
use think\Request;
use think\Cache;
use think\Session;
use app\common\model\Wxapp as WxappModel;
use app\common\model\StoreUser as StoreUserModel;
use app\common\model\ShopClerk as ShopClerkModel;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\Dealer as DealerModel;
use app\common\model\Setting as SettingModel;
use app\common\model\Config as ConfigModel;
use app\common\model\WebSet;
use app\common\library\wechat\WxPay;
	
	/**
	 * 生成审核提醒模板消息 - 公众号
	 */
	function sand_examine_msg($id,$title,$status,$wxapp_id='')
	{
		$tplmsg = WebSet::getItem('tplmsg');	//获取模板消息编号
		$wxapp = WebSet::getItem('wxapp');	//获取商家助手小程序
		$msg = [
			'touser' => '',
			'template_id' => $tplmsg['examine']['template_id'],
			'miniprogram' => [
				'appid' => $wxapp['app_id'],
				'pagepath' => 'pages/index/index'
			],
			'data' => [
				'first' => [
					'value' => '您有一条最新信息',
					'color' => '#173177'
				],
				'keyword1' => [
					'value' => $title,
					'color' => '#173177'
				],
				'keyword2' => [
					'value' => $id,
					'color' => '#173177'
				],
				'keyword3' => [
					'value' => date('Y/m/d H:i:s',time()),
					'color' => '#173177'
				],
				'keyword4' => [
					'value' => $status,
					'color' => '#173177'
				],
				'remark' => [
					'value' => '请及时关注新的动态提醒。',
					'color' => '#173177'
				]
			]
		];
		return f_tpl_msg($msg,1,$shop_id='',$wxapp_id);
	}
	
	/**
	 * 生成新订单提醒模板消息 - 公众号
	 */
	function make_new_order_msg($order)
	{
		if($order['table_id']==2){
			$title = '自取';
		}elseif($order['table_id']==3){
			$title = '外卖';
		}else{
			$title = '堂食';
		}
		$tplmsg = WebSet::getItem('tplmsg');	//获取模板消息编号
		$wxapp = WebSet::getItem('wxapp');	//获取商家助手小程序
		return $msg = [
			'touser' => '',
			'template_id' => $tplmsg['new_order']['template_id'],
			'miniprogram' => [
				'appid' => $wxapp['app_id'],
				'pagepath' => 'pages/order/index'
			],
			'data' => [
				'first' => [
					'value' => '收到一个新的'.$title.'订单',
					'color' => '#173177'
				],
				'keyword1' => [
					'value' => $order['order_no'],
					'color' => '#173177'
				],
				'keyword2' => [
					'value' => '￥'.$order['pay_price'].'元',
					'color' => '#173177'
				],
				'keyword3' => [
					'value' => $order['create_time'],
					'color' => '#173177'
				],
				'remark' => [
					'value' => '请及时处理您的订单。',
					'color' => '#173177'
				]
			]
		];
	}
	/**
	 * 发布模板消息 - 公众号
	 * $model 1=管理员，2=店长，3=店员，8=管理员+店长，9=所有人员
	 */
	function f_tpl_msg($msg,$mode,$shop_id='',$wxapp_id='')
	{
		$open_id = [];
		if($mode==1 OR $mode>=8){
			if(empty($wxapp_id)){
				$wxapp = WxappModel::detail();
			}else{
				$wxapp = WxappModel::getWxapp(['wxapp_id' => $wxapp_id]);
			}
			$store = StoreUserModel::detail($wxapp['store_user_id']);
			array_push($open_id,$store['wechat_open_id']);
		}
		if($mode>1){
			$model = new ShopClerkModel;
			$clerk = $model->getLists($shop_id,$wxapp_id);	
			for($n=0;$n<sizeof($clerk);$n++){
				if($mode==2 OR $mode==8){
					if($clerk[$n]['status']['value']==20){
						$store = StoreUserModel::getStore(['union_id' => $clerk[$n]['union_id']]);
						array_push($open_id,$store['wechat_open_id']);
					}
				}
				if($mode==3){
					if($clerk[$n]['status']['value']==10){
						$store = StoreUserModel::getStore(['union_id' => $clerk[$n]['union_id']]);
						array_push($open_id,$store['wechat_open_id']);
					}
				}
				if($mode==9){
					$store = StoreUserModel::getStore(['union_id' => $clerk[$n]['union_id']]);
					array_push($open_id,$store['wechat_open_id']);
				}
			}
		}		
		$access_token = getAccessToken('',0);
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		$open_id = array_unique($open_id);
		for($n=0;$n<sizeof($open_id);$n++){
			$msg['touser'] = $open_id[$n];
			$data = json_encode($msg,JSON_UNESCAPED_UNICODE);
			$result = json_decode(http_request($url,$data),true);
			write_log($result,__DIR__);
			//if($result['errcode']==0){
				//return $result['msgid'];
			//}
		}
		return true;
	}

	/**
     * 分销-分账
     */
	function dealer($order_id){
		$order = OrderModel::getOrder($order_id);
		$order_price = $order['total_price'] - $order['activity_price'];//计算消费商品金额，不含餐盒等费用
		$second_price = 0; //二级佣金
		$first_money = 0; //一级佣金
		$set = SettingModel::getItem('dealer',$order['wxapp_id']);
		if($set['is_open']==1){
			$user = UserModel::getUser(['user_id' => $order['user_id']]);//获取上家用户
			if($user['recommender']['value']>0){
				$second_price = round($order_price*$set['second_money']/100,2);//计算二级佣金-四舍五入保留2位小数
				$second = UserModel::getUser(['user_id' => $user['recommender']['value']]);//获取二级上家用户
				if($second['recommender']['value']>0){
					$first_money = round($order_price*$set['first_money']/100,2);//计算一级佣金-四舍五入保留2位小数
					$first = UserModel::getUser(['user_id' => $second['recommender']['value']]);//获取一级上家用户
					$first->commission = ['inc',$first_money];
					$first->save();
					$model = new DealerModel;	//添加进账记录
					$model->save([
						'user_id' => $first['user_id'],
						'price' => $first_money,
						'order_id' => $order['order_id'],
						'wxapp_id' => $order['wxapp_id']
					]);
				}
				$second->commission = ['inc',$second_price];
				$second->save();
				$model = new DealerModel;	//添加进账记录
				$model->save([
					'user_id' => $second['user_id'],
					'price' => $second_price,
					'order_id' => $order['order_id'],
					'wxapp_id' => $order['wxapp_id']
				]);
			}
			$order['commission'] = $first_money+$second_price;
			$order->save();
		}
	}

	/**
     * 获取已设置的所有类目
     */
	function getCategory()
	{
		$access_token = getAccessToken();
		if($access_token){
			$url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token='.$access_token;
			return json_decode(curl($url),true);
		}
		return false;
	}
	
	/**
     * 获取令牌 - 开放平台
	 * $type 请求类型 1商户小程序，0官方公众号
    */
	function getAccessToken($wxapp_id='',$type=1)
	{
		if($type==1){
			//商户小程序
			if(empty($wxapp_id)){
				$wxapp = WxappModel::detail();
			}else{
				$wxapp = WxappModel::getWxapp(['wxapp_id' => $wxapp_id]);
			}
			if($wxapp['is_empower']['value']==0){
				return false;	//未授权
			}
			if($wxapp['expires_in'] >= time()){
				$access_token=$wxapp['access_token'];
			}else{
				//重新获取
				$config = ConfigModel::detail();	//获取第三方配置
				$url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$config['component_access_token'];
				$data ='{"component_appid": "'.$config['app_id'].'","authorizer_appid": "'.$wxapp['app_id'].'","authorizer_refresh_token": "'.$wxapp['authorizer_refresh_token'].'"}';
				$token = json_decode(http_request($url,$data),true);
				$access_token = $token['authorizer_access_token'];
				$wxapp->access_token = $token['authorizer_access_token'];
				$wxapp->expires_in = time()+7000; //2个小时候过期，少加200秒
				//$wxapp['authorizer_refresh_token'] = $token['authorizer_refresh_token'];
				$wxapp->save();//保存最新的令牌access_token和过期时间
			}
		}else{
			//官方公众号
			$config = ConfigModel::detail();	//获取第三方配置
			if($config['wechat_at_expires'] >= time()){
				$access_token=$config['wechat_access_token'];
			}else{
				$url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$config['component_access_token'];
				$data ='{"component_appid": "'.$config['app_id'].'","authorizer_appid": "'.$config['wechat_appid'].'","authorizer_refresh_token": "'.$config['wechat_refresh_token'].'"}';
				$token = json_decode(http_request($url,$data),true);
				$access_token = $token['authorizer_access_token'];
				$config->wechat_access_token = $token['authorizer_access_token'];
				$config->wechat_at_expires = time()+7000; //2个小时候过期，少加200秒
				//$config['authorizer_refresh_token'] = $token['authorizer_refresh_token'];
				$config->save();//保存最新的令牌access_token和过期时间
			}			
		}
		return $access_token;
	}
	
	/**
	* 获取预授权码 - 生成授权页面
	* $type，1=授权公众号，2=授权小程序，3=两者都有
	*/
	function authUrl($appid, $access_token,$type=3)
	{
		if($type==1){
			$redirect_uri = web_url().'wechat.php&auth_type='.$type;
		}else{
			$redirect_uri = web_url().'authorize.php&auth_type='.$type;
		}
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$access_token;
		$data = '{"component_appid": "'.$appid.'"}';
		$result = json_decode(http_request($url,$data),true);//返回"pre_auth_code": "预授权码","expires_in": 有效期（600秒）
		$url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$appid.'&pre_auth_code='.$result['pre_auth_code'].'&redirect_uri='.$redirect_uri;
		return $url;
	}

	/**
	 * 获取授权信息
	*/
	function getAuth($appid, $access_token, $auth_code)
	{
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$access_token;
		$data = '{"component_appid":"'.$appid.'","authorization_code": "'.$auth_code.'"}';
		return json_decode(http_request($url,$data),true);	
	}

	/**
	 * 获取授权应用的帐号基本信息
	*/
	function getAppInfo($appid, $access_token, $auth_appid)
	{
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$access_token;
		$data = '{"component_appid":"'.$appid.'","authorizer_appid": "'.$auth_appid.'"}';
		return json_decode(http_request($url,$data),true);	
	}
	
	/**
	* 上传临时素材
	*/
	function up_temp_material($file_name)
	{
		$access_token = getAccessToken();
		$real_path = WEB_PATH . 'uploads/'.$file_name;
		$url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=image';
		$data['media'] = curl_file_create($real_path,'image/jpeg',$file_name);//获取要上传的二进制文件
		$result = json_decode(http_request($url,$data),true);
		return $result['media_id']; //返回的临时素材（media_id）
	}
	
	/**
	 * 永久素材
     * 上传图文消息内的图片 - 到微信端
	 *	图片仅支持jpg/png格式，大小必须在1MB以下
     */
    function upWechatUrl($file_name)
    {
        $access_token = getAccessToken();
		$real_path = WEB_PATH . 'uploads/'.$file_name;
		//上传到微信服务器
		$url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$access_token;
		$post['media'] = curl_file_create($real_path,'image/jpeg',$file_name);//获取要上传的二进制文件
		$res = json_decode(http_request($url,$post),true);
		if(!isset($res['url'])){
			return false;//上传错误，一般是图片不符合要求
		}
		return $res['url'];
    }
	
	/**
     * 获取粉丝用户基本信息（包括UnionID机制）- 公众号
    */
	function getWechatUserInfo($openid)
	{
		$access_token = getAccessToken('',0);
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		$result = json_decode(curl($url),true);
		if(isset($result['unionid'])){
			return [
				'union_id' => $result['unionid'],
				'wechat_open_id' => $result['openid'],
				'nickName' => $result['nickname'],
				'avatarUrl' => $result['headimgurl'],
				'gender' => $result['sex'],
				'country' => $result['country'],
				'province' => $result['province'],
				'city' => $result['city']
			];
		}
		return false;
	}
	
	/**
	* 验证手机号是否正确
	*/
	function isMobile($mobile) {
		if (!is_numeric($mobile)) {
			return false;
		}
		return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
	}

	/**
	 * 生成订单号
	 */
	function orderNo()
	{
		return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	}
	
	/**
     * 计算距离
	 * $from 起点，$to 终点
	 * $mode 计算方式：driving（驾车）、walking（步行）
     */
	function getDistance($from,$to,$mode='driving'){
		$values = WebSet::getItem('web');	//获取配置
		$key = $values['wxmap'];
		$url = 'https://apis.map.qq.com/ws/distance/v1/?parameters';
        $result = json_decode(curl($url, [
            'mode' => $mode,
			'from' => $from,
            'to' => $to,
            'key' => $key            
        ]), true);
        if ($result['status']!=0) {
            return false;
        }
        return $result['result']['elements'];
	}
	
	/**
     * 逆地址解析(坐标位置描述)
     */
	function getLocation($location){
		$values = WebSet::getItem('web');	//获取配置
		$key = $values['wxmap'];
		$url = 'https://apis.map.qq.com/ws/geocoder/v1/?location='.$location.'&key='.$key;
        $result = json_decode(curl($url), true);
        if ($result['status']!=0) {
            return false;
        }
        return $result['result']['address_component'];
	}
	
	/**
     * 将xml转为array
    */
	function _xmlToArr($xml) {
        $res = @simplexml_load_string ( $xml,NULL, LIBXML_NOCDATA );
        $res = json_decode ( json_encode ( $res), true );
        return $res;
    }
	
	/**
	 * 生成圆形图片
	 * @param $imgpath  图片地址/支持微信、QQ头像等没有后缀的网络图
	 * @param $saveName string 保存文件名，默认空。
	 * @return resource 返回图片资源或保存文件
	 */
	function yuan_img($imgpath) {
		$src_img = imagecreatefromstring(file_get_contents($imgpath));
		$w = imagesx($src_img);$h = imagesy($src_img);
		$w = $h = min($w, $h);
		imagesavealpha($src_img, true); //保留透明背景
		$img = imagecreatetruecolor($w, $h);//生成画布默认黑色
		imagealphablending($img,false); //保留透明背景
		//这一句一定要有
		imagesavealpha($img, true);
		//拾取一个完全透明的颜色,最后一个参数127为全透明
		$bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
		imagefill($img, 0, 0, $bg);
		$r   = $w / 2; //圆半径
		for ($x = 0; $x < $w; $x++) {
			for ($y = 0; $y < $h; $y++) {
				$rgbColor = imagecolorat($src_img, $x, $y);
				if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
					imagesetpixel($img, $x, $y, $rgbColor);
				}
			}
		}
		//返回资源
		//if(!$saveName) return $img;
		//输出图片到文件
		imagepng ($img,$imgpath);
		//释放空间
		imagedestroy($src_img);
		imagedestroy($img);
	}

	/**
	 * 打印调试函数
	 */
	function pre($content, $is_die = true)
	{
		header('Content-type: text/html; charset=utf-8');
		echo '<pre>' . print_r($content, true);
		$is_die && die();
	}

	/**
	 * 驼峰命名转下划线命名
	 */
	function toUnderScore($str)
	{
		$dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
			return '_' . strtolower($matchs[0]);
		}, $str);
		return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
	}

	/**
	 * 生成密码hash值
	 */
	function hema_hash($password)
	{
		return md5(md5($password) . 'hema_salt_SmTRx');
	}

	/**
	 * 获取api接口域名(小程序服务器域名)
	 */
	function api_url()
	{
		$config = ConfigModel::detail();	//获取第三方配置
		$domain = explode(';',$config['api_domain']);
		return 'https://'.$domain[0].'/';
	}
	
	/**
	 * 获取当前站点域名
	 */
	function web_url()
	{
		$request = Request::instance();
		$subDir = str_replace('\\', '/', dirname($request->server('PHP_SELF')));
		return $request->scheme() . '://' . $request->host() . $subDir . ($subDir === '/' ? '' : '/');
	}

	/**
	 * 写入日志
	 */
	function write_log($values, $dir)
	{
		if (is_array($values))
			$values = print_r($values, true);
		// 日志内容
		$content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
		try {
			// 文件路径
			$filePath = $dir . '/logs/';
			// 路径不存在则创建
			!is_dir($filePath) && mkdir($filePath, 0755, true);
			// 写入文件
			return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
		} catch (\Exception $e) {
			return false;
		}
	}

	/**
	 * curl请求指定url(POST请求)
	 * $url请求的URL
	 * $data 请求传递的数据
	 */
	function http_request($url,$data = null,$headers=array())
	{
		$curl = curl_init();
		if( count($headers) >= 1 ){
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		}
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}

	/**
	 * curl请求指定url
	 */
	function curl($url, $data = [])
	{
		// 处理get数据
		if (!empty($data)) {
			$url = $url . '?' . http_build_query($data);
		}
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}

	if (!function_exists('array_column')) {
		/**
		 * array_column 兼容低版本php
		 * (PHP < 5.5.0)
		 * @param $array
		 * @param $columnKey
		 * @param null $indexKey
		 * @return array
		 */
		function array_column($array, $columnKey, $indexKey = null)
		{
			$result = array();
			foreach ($array as $subArray) {
				if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
					$result[] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
				} elseif (array_key_exists($indexKey, $subArray)) {
					if (is_null($columnKey)) {
						$index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
						$result[$index] = $subArray;
					} elseif (array_key_exists($columnKey, $subArray)) {
						$index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
						$result[$index] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
					}
				}
			}
			return $result;
		}
	}

	/**
	 * 多维数组合并
	 */
	function array_merge_multiple($array1, $array2)
	{
		$merge = $array1 + $array2;
		$data = [];
		foreach ($merge as $key => $val) {
			if (
				isset($array1[$key])
				&& is_array($array1[$key])
				&& isset($array2[$key])
				&& is_array($array2[$key])
			) {
				$data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
			} else {
				$data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
			}
		}
		return $data;
	}

	/**
	 * 获取全局唯一标识符
	 */
	function getGuidV4($trim = true)
	{
		// Windows
		if (function_exists('com_create_guid') === true) {
			$charid = com_create_guid();
			return $trim == true ? trim($charid, '{}') : $charid;
		}
		// OSX/Linux
		if (function_exists('openssl_random_pseudo_bytes') === true) {
			$data = openssl_random_pseudo_bytes(16);
			$data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
			$data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
			return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
		}
		// Fallback (PHP 4.2+)
		mt_srand((double)microtime() * 10000);
		$charid = strtolower(md5(uniqid(rand(), true)));
		$hyphen = chr(45);                  // "-"
		$lbrace = $trim ? "" : chr(123);    // "{"
		$rbrace = $trim ? "" : chr(125);    // "}"
		$guidv4 = $lbrace .
			substr($charid, 0, 8) . $hyphen .
			substr($charid, 8, 4) . $hyphen .
			substr($charid, 12, 4) . $hyphen .
			substr($charid, 16, 4) . $hyphen .
			substr($charid, 20, 12) .
			$rbrace;
		return $guidv4;
	}
